package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.BannedUserCache;
import com.conversationboard.model.User;

@WebServlet(name = "AdminUnbanUserControllerServlet", urlPatterns = "/Admin/AdminUnbanUserControllerServlet")
public class AdminUnbanUserControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -7939024439252774251L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		String referrer = request.getHeader("Referer");
		request.setAttribute("referrer", referrer);

		try {

			String userIdToBeUnbanned = (String) request.getParameter("userid");
			String ipAddressToBeUnbanned = (String) request.getParameter("ipaddress");
			int boardId = Integer.parseInt(request.getParameter("boardid"));
			String adminId = request.getUserPrincipal().getName();

			/* Check if you're authorised */
			User user = User.get(adminId);

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (!user.isBoardAdmin(boardId)) {
				request.setAttribute("message", "You are not authorised to perform that operation.");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			BannedUserCache.unban(user, userIdToBeUnbanned);
			BannedUserCache.unban(user, ipAddressToBeUnbanned);

			request.setAttribute("message", "User has been unbanned successfully");

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}
